/*
 * Copyright (C) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <cstdlib>
#include <hilog/log.h>
#include "Embeddedcomponent.h"
#include <QWindow>
#include <QtCore/qopenharmony.h>
#include <QtCore/QJsObject>

#define APP_LOG_TAG "XComponent_Native"
const unsigned int LOG_PRINT_DOMAIN = 0xFF00;

ArkTsInst EmbeddedComponent::m_inst;

napi_value EmbeddedComponent::RegisterXComponent(napi_env env, napi_callback_info info)
{
    size_t argc = 1;
    napi_value args[1] = {nullptr};
    napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
    m_inst.env = env;
    napi_value createMixedEmbedded; // ptr_function
    napi_get_named_property(env, args[0], "createMixedXComponent", &createMixedEmbedded);
    napi_create_reference(env, createMixedEmbedded, 1, &EmbeddedComponent::m_inst.createFunc);
    return nullptr;
}

ArkUI_NodeHandle EmbeddedComponent::CreateComponent(QString engineid, QString route)
{
    ArkUI_NodeHandle result = nullptr;
    QtOh::runOnJsUIThreadAndWait([&] {
        napi_value out; // {content:xxx}
        napi_value func;
        int argc = 2;
        napi_value argv[2];
        QByteArray byteArr = engineid.toUtf8();
        napi_create_string_utf8(m_inst.env, byteArr.constData(), byteArr.length(), argv);
        QByteArray routeArr = route.toUtf8();
        napi_create_string_utf8(m_inst.env, routeArr.constData(), routeArr.length(), argv+1);
        // 在主线程中创建EWNode（这是关键操作，必须在主线程执行）
        napi_get_reference_value(m_inst.env, EmbeddedComponent::m_inst.createFunc, &func);
        napi_call_function(m_inst.env, nullptr, func, argc, argv, &out);
        // 获取ArkTS的NodeHandle
        napi_value componentContent = nullptr;
        napi_get_named_property(m_inst.env, out, "content", &componentContent);
        if (componentContent == nullptr) {
            OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "CreateComponent",
                "componentContent is null");
            return;
        }
        ArkUI_NodeHandle handle;
        int res = OH_ArkUI_GetNodeHandleFromNapiValue(m_inst.env, componentContent, &handle);
        if (res != ARKUI_ERROR_CODE_NO_ERROR) {
            OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "CreateComponent",
                "OH_ArkUI_GetNodeHandleFromNapiValue failed");
            return;
        }
        result = handle;
    });
    return result;
}
